/**
 * 全局 env
 */

import lodash from 'lodash';
import Promise from 'bluebird';
import SessionModel from '../models/session';

import UI from './ui';

const TTXS = lodash.assign({
    assetsBaseURL: 'https://st0.dancf.com/',
    assetsPrefix: 'wechat-gym/',

    // default grades
    GRADES: {
        VIP: 1
    },
    user: null,

    // show error
    showError(err) {
        return UI.showError(err);
    }
}, global.TTXS);

// userId, isVipUser
Object.defineProperties(TTXS, {
    userId: {
        get: function() {
            var user = this.user || {};

            return user.id || 0;
        }
    }
});

// login, logout
TTXS.login = function(data) {
    let user = new SessionModel(data);

    if(data.id) {
        TTXS.user = user;

        return Promise.resolve(user);
    }

    return user.$save()
    .then(function(user) {
        TTXS.user = user;

        return user;
    });
};
TTXS.logout = function() {
    TTXS.user = null;

    return SessionModel.delete().$promise;
};

// isAuthorized
TTXS.isAuthorized = function(grade) {
    var user = TTXS.user;

    if(!+grade) {
        grade = 0;
    }

    return user && user.admin_grade >= grade;
};

// // auauthorized
// TTXS.auauthorized = function() {
//     return !!TTXS.user_id;
// };

if(process.env.NODE_ENV === 'development') {
    global.TTXS = TTXS;
}

export default TTXS;
